package com.erp.util;

import java.util.List;

import com.erp.dto.Privilege;

public class PrivilegeUtil {

	/**
	 * 根据权限List获得zTree要求的json格式 （格式： [{id:1, pId:0, name: "父节点1"}, {id:11,
	 * pId:1,name: "子节点1"}]）
	 * 
	 * @param privilegeList
	 *            原始权限List（全部）
	 * @param checkedPrivilegeList
	 *            用户权限List（前台显示默认选中）
	 * @return
	 */
	public static String toPrivilegeTree(List<Privilege> privilegeList,
			List<Privilege> checkedPrivilegeList) {
		String treeJson = "[";
		treeJson += "{id:" + privilegeList.get(0).getId() + ",pId:"
				+ privilegeList.get(0).getParentId() + ",name:\""
				+ privilegeList.get(0).getName() + "\",open:true";
		for (Privilege privilege : checkedPrivilegeList) {
			if (privilegeList.get(0).equals(privilege)) {
				treeJson += ",checked:true";
			}
		}
		treeJson += "}";
		for (int i = 1; i < privilegeList.size(); i++) {
			treeJson += ",{id:" + privilegeList.get(i).getId() + ",pId:"
					+ privilegeList.get(i).getParentId() + ",name:\""
					+ privilegeList.get(i).getName() + "\",open:true";
			for (Privilege privilege : checkedPrivilegeList) {
				if (privilegeList.get(i).equals(privilege)) {
					treeJson += ",checked:true";
				}
			}
			treeJson += "}";
		}
		treeJson += "]";
		return treeJson;
	}

	/**
	 * 判断请求的URL是否有权限
	 * 
	 * @param url
	 *            请求的URL
	 * @param validPrivilegeList
	 *            用户的权限List
	 * @param allPrivilegeList
	 *            所有被控制的权限List
	 * @return 请求的URL不受控制或受控制但有权限则返回true
	 */
	public static boolean isValid(String url,
			List<Privilege> validPrivilegeList, List<Privilege> allPrivilegeList) {

		// if (url.endsWith("Page")) {
		// url = url.substring(0, url.length() - 4);
		// }
		
		
		String[] relatedPrivilege;
		int count = 0;
		String privilegeUrl = "";
		if (allPrivilegeList != null) {
			for (Privilege p : allPrivilegeList) {
				// 判断是否有权限
				privilegeUrl = p.getUrl();
				if (privilegeUrl != null && !"".equals(privilegeUrl)) {
					relatedPrivilege = privilegeUrl.split(",");
					for (int i = 0; i < relatedPrivilege.length; i++) {
						if (url.equals(relatedPrivilege[i])) {
							count++;
						}
					}
				}

			}
		}

		// count值为0表示url不纳入控制
		// url不纳入控制或合法则返回true
		if (count == 0) {
			return true;
		} else {
			for (Privilege p : validPrivilegeList) {
				// 判断是否有权限
				privilegeUrl = p.getUrl();
				if (privilegeUrl != null && !"".equals(privilegeUrl)) {
					relatedPrivilege = privilegeUrl.split(",");
					for (int i = 0; i < relatedPrivilege.length; i++) {
						if (url.equals(relatedPrivilege[i])) {
							return true;
						}
					}
				}
			}
		}
		// 否则返回false
		return false;
	}
}
